package kr.ac.kongju.gedl.cmmn.web;

import java.util.HashMap;
import java.util.List;

import kr.ac.kongju.gedl.code.dao.CodeDAO;
import kr.ac.kongju.gedl.code.vo.CodeInfoVO;

public class CU {

	public final static String TREE_TYPE = "TREE";
	private static CodeDAO codeDAO = null;
	
	private HashMap<String, CodeInfoVO> codeMap = null;
	private HashMap<String, List<CodeInfoVO>> codeListMap = null;
	
	private static CU codeUtil = null;
	
	public static CU getInstance() {
		if(codeUtil == null) {
			synchronized(CU.class) {
				codeUtil = new CU();
			}
		}
		return codeUtil;
	}
	
	private CU() {
		init();
	}
	
	private void init() {
		codeDAO = (CodeDAO)SpringContextManager.getInstance().getContext().getBean("codeDAO");
		codeMap = new HashMap<String, CodeInfoVO>();
		codeListMap = new HashMap<String, List<CodeInfoVO>>();
		//setCodeMap();	// 모든 코드 메모리에 등록
	}
	
	public CodeInfoVO getCodeInfo(String codeID) throws Exception{
		if(codeMap.get(codeID) != null) {
			return (CodeInfoVO)codeMap.get(codeID);
		} else {
			CodeInfoVO codeInfo = codeDAO.retrieveCodeInfo(new CodeInfoVO(codeID));
			if(codeInfo != null) {
				codeMap.put(codeInfo.getCodeId(), codeInfo);
			}
			return codeDAO.retrieveCodeInfo(new CodeInfoVO(codeID));
		}
	}
	
	public String getCodeName(String codeID) throws Exception{
		CodeInfoVO info = CU.getInstance().getCodeInfo(codeID);
		return info != null ? info.getCodeName() : "";
	}
	
	public List<CodeInfoVO> getCodeList(CodeInfoVO codeInfo) throws Exception{
		return codeDAO.retrieveListCodeInfo(codeInfo);
	}
	
	public List<CodeInfoVO> getCodeList(String parent) throws Exception{
		List<CodeInfoVO> codeList = null;
		if(codeListMap.get(parent) != null) {
			codeList = codeListMap.get(parent);
		} else {
			CodeInfoVO codeInfo = new CodeInfoVO();
			codeInfo.setParent(parent);
			codeList = codeDAO.retrieveListCodeInfo(codeInfo);
			codeListMap.put(parent, codeList);
		}
		
		return codeList;
	}
	
	/**
	 * 모든 공통코드 메모리에 담는다.
	 * instance가 생성될때 초기화 메소드에서 호출
	 */
	private void setCodeMap() {
		int totalCount = 0;
		int rowPerPage = 500;
		int totPage = 0;
		try {
			totalCount = codeDAO.retrieveListCountCodeInfo(null);
			totPage = (totalCount / rowPerPage)+1;
			for(int i = 1; i <= totPage; i++) {
				CodeInfoVO codeInfo = new CodeInfoVO();
				codeInfo.setPage(i);
				codeInfo.setRowPerPage(rowPerPage);
				putCodeMap(codeDAO.retrieveListCodeInfo(codeInfo));
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 코드정보 목록을 메모리에 담는다.
	 * @param codeInfo 코드정보 목록
	 */
	private void putCodeMap(List<CodeInfoVO> codeInfoList) {
		if(codeInfoList != null && codeInfoList.size() > 0) {
			for(CodeInfoVO codeInfo : codeInfoList) {
				codeMap.put(codeInfo.getCodeId(), codeInfo);
			}
		}
	}
}
